package com.angel.bo.common.controller;

import com.angel.bo.common.msg.WebReturn;
import com.angel.bo.common.service.BaseService;
import com.angel.bo.common.vo.Query;
import com.xiaoleilu.hutool.bean.BeanUtil;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import javax.servlet.http.HttpServletRequest;
import java.util.Map;


/**
 * @Author:
 * @Description:
 * @Date: 18:26 2018/1/25
 * @update by zhangwei at 2018/1/29  去掉BaseController里所有方法上的Mapping,
 * 目的是为了防止一些本不需要暴露的接口(如:城市的增删改等),由于继承了BaseController而暴露出去,
 * 造成数据被破坏的风险.
 */
public class BaseController<Biz extends BaseService, Entity> {

    @Autowired
    protected HttpServletRequest request;
    @Autowired
    protected Biz baseBiz;


    @PostMapping("/add")
    @ApiOperation(value = "添加对象")
    public WebReturn<Entity> add(@RequestBody Entity entity) {
        baseBiz.insertSelective(entity);
        return new WebReturn<>(entity);
    }

    @RequestMapping(value = "/get", method = RequestMethod.POST)

    public WebReturn<Entity> get(Integer id) {
        return new WebReturn<>(baseBiz.selectById(id));
    }


    @RequestMapping(value = "/update", method = RequestMethod.POST)
    public WebReturn<Entity> update(@RequestBody Entity entity) {
        baseBiz.updateSelectiveById(entity);
        return new WebReturn<>(entity);
    }

    @RequestMapping(value = "/remove", method = RequestMethod.POST)
    public WebReturn<Entity> remove(Integer id) {
        baseBiz.deleteById(id);
        return new WebReturn<>();
    }

    @RequestMapping(value = "/all", method = RequestMethod.POST)
    public WebReturn<Entity> all(@RequestBody Entity entity) {
        return new WebReturn<>(baseBiz.selectList(entity));
    }


    @PostMapping("/page")
    @ApiOperation(value = "返回分页列表",notes = "默认前10条数，模糊查找")
    public WebReturn<Entity> list(Integer pageNum, Integer pageSize, Entity entity) {
        Map<String, Object> map = BeanUtil.beanToMap(entity);
        Query query = new Query(map, pageNum, pageSize);
        return baseBiz.selectByQuery(query);
    }
}
